package v1

import (
	"fmt"
	"ginblog/model"
	"ginblog/utils/errmsg"
	"github.com/gin-gonic/gin"
	"net/http"
	"strconv"
)

// 添加用户

func AddUser(c *gin.Context) {
	// todo 添加用户
	var data model.User
	// 接收参数失败的情况
	if err := c.ShouldBindJSON(&data); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"status": 500,
			"data":   "发送数据错误",
			"msg":    err.Error(),
		})

		return
	}
	/*
		1、检查用户名是否存在
		2、存入数据库
	*/
	code := model.CheckUser(data.Username)
	if code == errmsg.SUCC {
		model.CreateUser(&data)
	}

	c.JSON(http.StatusOK, gin.H{
		"status": code,
		"data":   data,
		"msg":    errmsg.GetErrorMsg(code),
	})

}

// 查询单个用户

// 查询用户列表
func GetUsers(c *gin.Context) {

	/*
		接收pageSize 和pageNum
		使用 strconv.Atoi 转化为 int 类型
	*/
	var code int
	var data []model.User
	pageSize, pageSizeErr := strconv.Atoi(c.Query("pageSize"))
	pageNum, pageNumErr := strconv.Atoi(c.Query("pageNum"))
	if pageSizeErr != nil || pageNumErr != nil {
		code = errmsg.ERROR_PARMENTS
		data = nil
	} else {
		if pageSize == 0 {
			pageSize = -1
		}
		if pageNum == 0 {
			pageNum = -1
		}
		data, code = model.GetUserList(pageSize, pageNum)

	}
	c.JSON(http.StatusOK, gin.H{
		"status": code,
		"data":   data,
		"msg":    errmsg.GetErrorMsg(code),
	})

}

// 编辑用户
func EditUser(c *gin.Context) {
	var data model.User
	c.ShouldBindJSON(&data)
	id, _ := strconv.Atoi(c.Param("id"))
	code := model.CheckUser(data.Username)
	if code == errmsg.SUCC {
		model.EditUser(id, &data)
	}
	if code == errmsg.ERROR_USERNAME_USED {
		fmt.Println("%v", data)
		c.Abort()
	}
	c.JSON(http.StatusOK, gin.H{
		"status": code,
		"msg":    errmsg.GetErrorMsg(code),
	})

}

// 删除用户
func DeleteUser(c *gin.Context) {
	id, _ := strconv.Atoi(c.Param("id"))
	code := model.DeleteUser(id)
	c.JSON(http.StatusOK, gin.H{
		"status": code,
		"msg":    errmsg.GetErrorMsg(code),
	})

}
